package model

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"database/sql/driver"
	"gorm.io/gorm"
)

// 自定义model字段数据类型 -> jsonb(数据库类型)
type GormList []string

// 实现 sql.Scanner 接口，Scan 将 value 扫描至 Jsonb
// 数据库字段取值映射到model字段时
func (g *GormList) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}
	return json.Unmarshal(bytes, &g)
}

// 实现 driver.Valuer 接口，Value 返回 json value
// model字段设置映射到数据库字段时
func (g GormList) Value() (driver.Value, error) {
	if len(g) == 0 {
		return nil, nil
	}
	return json.Marshal(g)
}

type BaseModel struct {
	ID        int64          `gorm:"primary_key;not_null;auto_increment" json:"id"`
	CreatedAt time.Time      `gorm:"column:add_time" json:"-"`
	UpdatedAt time.Time      `gorm:"column:update_time" json:"-"`
	DeletedAt gorm.DeletedAt `json:"-"`
	IsDeleted bool           `json:"-"`
}

type Page struct {
	Pages       int64
	PagePerNums int64
}
